using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SmartLink.Domain.Entity;
using SmartLink.IRepository;
using SmartLink.Repository.Base;
using Dapper;

namespace SmartLink.Repository
{
    public class PER_ActionPermissionsRoleRepo : RepositoryBase<PER_ActionPermissionsRole>, IPER_ActionPermissionsRoleRepo
    {
        /// <summary>
        /// 给角色分配动作权限 
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="actions"></param>
        /// <returns></returns>
        public bool AllotActionsToRole(int roleId, IList<int> actions)
        {
            bool results = false;
            using (DbTransaction tran = this.TranCreate())
            {
                try
                {
                    var repo = new RepositoryBase<PER_ActionPermissionsRole>();
                    repo.DeleteWhere(string.Format("delete from PER_ActionPermissionsRole where RID={0}", roleId), tran);
                    foreach (var actionId in actions)
                    {
                        PER_ActionPermissionsRole actionPermissionRole = new PER_ActionPermissionsRole();
                        actionPermissionRole.RID = roleId;
                        actionPermissionRole.AID = actionId;
                        repo.Add(actionPermissionRole, tran);
                    }
                    tran.Commit();
                    results = true;
                }
                catch (Exception ex)
                {
                    this.TranRollback(tran);
                    results = false;
                }
                finally
                {
                    this.TranClose(tran);
                }
            }
            return results;
        }

        public IList<PER_ActionPermissionsRole> GetActionsByRole(int roleId)
        {
            IList<PER_ActionPermissionsRole> results = new List<PER_ActionPermissionsRole>();
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                var sql = string.Format(" select * from PER_ActionPermissionsRole where RID=@RID");
                results = conn.Query<PER_ActionPermissionsRole>(sql, new { RID = roleId }).ToList();
            }
            return results;
        }
    }
}
